/**
 * @desc: 新增/编辑寄件地址信息面板弹框
 * @item {object} 需要用来回显的数据
 * @title {string} 标题
 * @visible { bool} 
 * @handleOK { func} 点击保存后的回调
 * @handleCancel {func} 点击取消弹框事件
 */

import React, { useState, useEffect } from 'react';
import { Form, Input, Cascader, Button, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import { layout1 } from '@/utils/config';
import { getAllArea, addMailAddress } from '@/services/common';
import { find } from 'lodash';
import { mobile } from '@/utils/rule';


const { TextArea } = Input

export default ({ item={}, title="添加寄件地址", visible, handleOk, handleCancel }) => {
 
  
  const [ mobiles, setMobile ] = useState(true);
  const [ phone, setPhone ] = useState(true);
  const [ data, setData ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ receiveObj, setObj ] = useState({});
  const [ form ] = Form.useForm();

  useEffect(() => {
    getAreaList();
  }, [])

  useEffect(() => {
    if(visible) {
      form.resetFields();
    }
  }, [ visible ])

  const getAreaList = async () => {
    const res = await getAllArea();
    if(res.success) {
      setData(res.data);
    }
  }

  const onChange = val => {
    const data = form.getFieldsValue();
    if (val == 1) {
        const { mobPhone } = data;
        if (mobPhone) {
            if (phone) {
                setPhone(false)
            }

        } else if (!phone) {
            setPhone(true)
        }
    } else {
        const { telPhone } = data;
        if (telPhone) {
            if (mobiles) {
                setMobile(false)
            }

        } else if (!mobiles) {
            setMobile(true)
        }
    }
  }

  const onOk = () => {
    if(loading) {
      return false;
    }
    form.validateFields().then(val => {
      handleSaveData(val)
    }).catch(err => {

    })
  }

  const handleSaveData = async val => {
    setLoading(true);
    //调用保存接口
    const { name, mobPhone, telPhone, area, address } = val;
    const obj1 = {
      name,
      mobPhone, 
      telPhone,
      areaId: area[2],
      address,
      type: 2,
      provinceId: area[0],
      cityId: area[1],
      provinceName: receiveObj.provinceName,
      cityName: receiveObj.cityName,
      areaName: receiveObj.areaName
    }
    const res = await addMailAddress(obj1);
    if(res.success) {
      message.success('保存成功！');
      handleOk(val);
    }
    let timer = setTimeout(() => {
      setLoading(false);
      clearTimeout(timer);
      timer = null;
    }, 300)
  }

  const handleChange = (val, option) => {
    const obj = {};
    obj.provinceName = option[0].name;
    obj.cityName = option[1].name;
    obj.areaName = option[2].name;
    setObj(obj);
  }

  const handleFormatData = () => {
    const val = form.getFieldValue('message');
    if (val) {
      try {
        const result = AddressParse.parse(val.replace(/\s+/g,''))[0];
        let provinceId,cityId,areaId;
        if(result.province && result.city && result.area) {
          const proObj = find(data, ['name', result.province.replace('省', '')]);
          provinceId = proObj.id;
          const cityObj = find(proObj.childs, ['name', result.city]);
          cityId = cityObj.id;
          const areaObj = find(cityObj.childs, ['name', result.area])
          areaId = areaObj.id;
          const obj2 = {};
          obj2.provinceName = result.province;
          obj2.cityName = result.city;
          obj2.areaName = result.area;
          setObj(obj2);
        }
        form.setFieldsValue({
          name: result.name,
          mobPhone: result.mobile,
          telPhone: result.phone,
          address: result.details.length > 120 ? result.details.slice(0, 120) : result.details,
          area: provinceId ? [provinceId, cityId, areaId] : undefined,
        })
      } catch (error) {
        console.log(error);
        message.error('地址识别失败');
      }
    } else {
        message.warning('请输入识别内容！')
    }
  }

  return (
    <CommonModal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={handleCancel}
      width='600px'
    >
        <Form { ...layout1 } form={form} initialValues={{ ...item }} name="add-mail-address">
          <Form.Item name="message" label="地址识别" extra='复制第三方订单详情页的收货地址，然后点击右侧的“一键识别” 如：【李**，13658626452，广东省 广州市 天河区 *********，000022】'>
            <div style={{ display: 'flex' }}>
              <TextArea rows={3}/>
              <Button style={{ marginLeft: '12px' }} onClick={handleFormatData}>一键识别</Button>
            </div>
          </Form.Item>
          <Form.Item name="name" label="寄件人" rules={
            [
              { required: true, message: '寄件人不能为空' }
            ]
          }>
            <Input placeholder="最多30个字符" maxLength="30" />
          </Form.Item>
          <Form.Item shouldUpdate name="mobPhone" label="手机号" rules={
            [
              { required: mobiles, message: '手机号和座机号至少填写一项' },
              mobile
            ]
          }>
            <Input maxLength={11} onChange={ () => onChange(1) } placeholder="请填写手机号，格式：18888888888" />
          </Form.Item>
          <Form.Item name="telPhone" label="座机号" rules={
            [
              { required: phone, message: '手机号和座机号至少填写一项',}
            ]
          }>
            <Input onChange={ () => onChange(2) } maxLength='15' placeholder="请填写座机号，格式：0573-88888888" />
          </Form.Item>
          <Form.Item name="area" label="所在地区" rules={
            [
              { required: true, message: '地区未选择' }
            ]
          }>
            <Cascader options={data} onChange={handleChange} fieldNames={{ label: 'name', value: 'id', children: 'childs' }} placeholder="请选择地区" />
          </Form.Item>
          <Form.Item name="address" label="详细地址" rules={
            [
              { required: true, message: '详细地址未填写',}
            ]
          }>
            <TextArea rows={4} maxLength="120" placeholder="最多120个字符" />
          </Form.Item>
        </Form>
       <CommonLoading loading={loading} />
    </CommonModal>
  )
}